﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 商品SKU规格
    /// </summary>
    [Route("admin/shop/sku")]
    [ApiController]
    public class ShopSukController : ControllerBase
    {
        private readonly IShopSkuService _shopSkuService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public ShopSukController(IShopSkuService shopSkuService, IUserService userService, IMapper mapper)
        {
            _shopSkuService = shopSkuService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/admin/shop/sku/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _shopSkuService.QueryAsync(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<ShopSkusDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/admin/shop/sku/view/10
        /// </summary>
        [HttpGet("view/{top}")]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.View)]
        public async Task<IActionResult> GetList([FromRoute] int top, [FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (!searchParam.Fields.IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据库列表
            var resultFrom = await _shopSkuService.QueryListAsync(top,
                x => (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))));

            //映射成DTO，根据字段进行塑形
            var resultDto = resultFrom.AsEnumerable().ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/admin/shop/sku?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _shopSkuService.QueryPageAsync<ShopSkus>(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.ParentId == 0
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "SortId,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopSkusListDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/admin/shop/sku
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] ShopSkusEditDto modelDto)
        {
            //写入数据库
            var resultFrom = await _shopSkuService.AddAsync(modelDto);
            var result = await _shopSkuService.QueryAsync(x => x.Id == resultFrom.Id);
            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/admin/shop/sku/1
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] ShopSkusEditDto modelDto)
        {
            var result = await _shopSkuService.UpdateAsync(id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 局部更新一条记录
        /// 示例：/admin/shop/sku/1
        /// Body：[{"op":"replace","path":"/title","value":"new title"}]
        /// </summary>
        [HttpPatch("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] JsonPatchDocument<ShopSkusEditDto> patchDocument)
        {
            var model = await _shopSkuService.QueryAsync<ShopSkus>(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }

            var modelToPatch = _mapper.Map<ShopSkusEditDto>(model);
            patchDocument.ApplyTo(modelToPatch, ModelState);
            //验证数据是否合法
            if (!TryValidateModel(modelToPatch))
            {
                return ValidationProblem(ModelState);
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelToPatch, model);
            await _shopSkuService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/shop/sku/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] long id)
        {
            if (!await _shopSkuService.ExistsAsync<ShopSkus>(x => x.Id == id))
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _shopSkuService.DeleteAsync<ShopSkus>(x => x.Id == id || x.ParentId == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/admin/shop/sku?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("ShopSku", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _shopSkuService.DeleteAsync<ShopSkus>(x => arrIds.Contains(x.Id)|| arrIds.Contains(x.ParentId));

            return NoContent();
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/merchant/shop/sku/1
        /// </summary>
        [HttpGet("/merchant/shop/sku/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //查询数据库获取实体
            var model = await _shopSkuService.QueryAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<ShopSkusDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/merchant/shop/sku/view/10
        /// </summary>
        [HttpGet("/merchant/shop/sku/view/{top}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromRoute] int top, [FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (!searchParam.Fields.IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据库列表
            var resultFrom = await _shopSkuService.QueryListAsync(top,
                x => x.IsDelete == 0
                && x.MerchantId == merchantModel.Id 
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))));

            //映射成DTO，根据字段进行塑形
            var resultDto = resultFrom.AsEnumerable().ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/merchant/shop/sku?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/merchant/shop/sku")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopSkusDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _shopSkuService.QueryPageAsync<ShopSkus>(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.IsDelete == 0
                && x.MerchantId == merchantModel.Id 
                && x.ParentId == 0
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "SortId,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopSkusListDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/merchant/shop/sku
        /// </summary>
        [HttpPost("/merchant/shop/sku")]
        [Authorize]
        public async Task<IActionResult> MerchantAdd([FromBody] ShopSkusEditDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }
            modelDto.MerchantId = merchantModel.Id;

            //写入数据库
            var resultFrom = await _shopSkuService.AddAsync(modelDto);
            var result = await _shopSkuService.QueryAsync(x => x.Id == resultFrom.Id);
            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/merchant/shop/sku/1
        /// </summary>
        [HttpPut("/merchant/shop/sku/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantUpdate([FromRoute] long id, [FromBody] ShopSkusEditDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }
            modelDto.MerchantId = merchantModel.Id;

            var result = await _shopSkuService.UpdateAsync(id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 局部更新一条记录
        /// 示例：/merchant/shop/sku/1
        /// Body：[{"op":"replace","path":"/title","value":"new title"}]
        /// </summary>
        [HttpPatch("/merchant/shop/sku/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantUpdate([FromRoute] long id, [FromBody] JsonPatchDocument<ShopSkusEditDto> patchDocument)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }
            var model = await _shopSkuService.QueryAsync<ShopSkus>(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }

            var modelToPatch = _mapper.Map<ShopSkusEditDto>(model);
            patchDocument.ApplyTo(modelToPatch, ModelState);
            //验证数据是否合法
            if (!TryValidateModel(modelToPatch))
            {
                return ValidationProblem(ModelState);
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelToPatch, model);
            await _shopSkuService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/merchant/shop/sku/1
        /// </summary>
        [HttpDelete("/merchant/shop/sku/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantDelete([FromRoute] long id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            var model = await _shopSkuService.QueryAsync<ShopSkus>(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"记录[{id}]不存在或已删除"));
            }
            model.IsDelete = 1; //标记删除
            //保存到数据库
            await _shopSkuService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/merchant/shop/sku?ids=1,2,3
        /// </summary>
        [HttpDelete("/merchant/shop/sku")]
        [Authorize]
        public async Task<IActionResult> MerchantDeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopSkuService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //找出符合条件的记录
            var list = await _shopSkuService.QueryListAsync<ShopSkus>(1000, x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && arrIds.Contains(x.Id), WriteRoRead.Write);
            if (list.Count() == 0)
            {
                return BadRequest(ResponseMessage.Error("没有找到需要删除的记录"));
            }
            foreach (var item in list)
            {
                item.IsDelete = 1; //标记删除
            }
            //保存到数据库
            await _shopSkuService.SaveAsync();

            return NoContent();
        }
        #endregion
    }
}
